package by.dvrudenko.avtobaza.dataaccess.impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.commons.lang3.Validate;
import org.hibernate.jpa.criteria.OrderImpl;
import org.springframework.stereotype.Repository;

import by.dvrudenko.avtobaza.dataaccess.UserDao;
import by.dvrudenko.avtobaza.datamodel.User;
import by.dvrudenko.avtobaza.datamodel.User_;
import by.dvrudenko.avtobaza.datamodel.enums.UserRole;


@Repository
public class UserDaoImpl extends AbstractDaoImpl<Long, User> implements UserDao{

	
	public UserDaoImpl() {
		super(User.class);
	}
	
	  @Override
	    public List<User> getAllUser() {
	        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

	        CriteriaQuery<User> criteria = cBuilder.createQuery(User.class);
	        Root<User> root = criteria.from(User.class);

	        criteria.select(root);

	        TypedQuery<User> query = getEm().createQuery(criteria);
	        List<User> results = query.getResultList();
	        return results;
	    }

	    @Override
	    public Long getCount() {
	        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

	        CriteriaQuery<Long> criteria = cBuilder.createQuery(Long.class);
	        Root<User> root = criteria.from(User.class);

	        criteria.select(cBuilder.count(root));

	        TypedQuery<Long> query = getEm().createQuery(criteria);
	        return query.getSingleResult();
	    }

	    @Override
	    public List<User> getAllUserByName(String name) {
	    	Validate.notNull(name, " - attributes can't be null");
	        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

	        CriteriaQuery<User> criteria = cBuilder.createQuery(User.class);
	        Root<User> root = criteria.from(User.class);

	        criteria.select(root);

	        criteria.where(cBuilder.equal(root.get(User_.name), name));

	        TypedQuery<User> query = getEm().createQuery(criteria);
	        List<User> results = query.getResultList();
	        return results;
	    }


}
